<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="医师" prop="doctorId">
            <el-select 
              v-model="queryParams.doctorId" 
              placeholder="请选择排班医师"
              clearable
              style="width: 150px"
             >
              <el-option
                v-for="doctor in doctorList"
                :key="doctor.id"
                :label="doctor.nickname"
                :value="doctor.id"
              />
            </el-select>
          </el-form-item>
      <el-form-item label="值班日期" prop="date">
        <el-date-picker
          v-model="queryParams.date"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="日期"
          class="!w-120px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="状态"
              clearable
              class="!w-100px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['medical:schedules:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['medical:schedules:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column label="排班编号" align="center" prop="id" />
      <el-table-column label="医师名称" align="center" prop="doctorName" />
      <el-table-column label="排班日期" align="center" prop="date" :formatter="dateFormatter2"/>
      <el-table-column label="上午开始时间" align="center" prop="morningStart" :formatter="timeArrayTableFormatter"/>
      <el-table-column label="上午结束时间" align="center" prop="morningEnd" :formatter="timeArrayTableFormatter"/>
      <el-table-column label="上午就诊上限" align="center" prop="morningCapacity" />
      <el-table-column label="下午开始时间" align="center" prop="afternoonStart" :formatter="timeArrayTableFormatter"/>
      <el-table-column label="下午结束时间" align="center" prop="afternoonEnd" :formatter="timeArrayTableFormatter"/>
      <el-table-column label="下午就诊上限" align="center" prop="afternoonCapacity" />
      <el-table-column label="状态" key="status">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="0"
                :inactive-value="1"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
      
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['medical:schedules:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['medical:schedules:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ScheduleForm ref="formRef" @success="getList" />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter2, timeArrayTableFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CommonStatusEnum } from '@/utils/constants'
import * as ScheduleApi from '@/api/medical/schedule/index'
import ScheduleForm from './ScheduleForm.vue'
import * as DoctorApi from '@/api/medical/doctor'

defineOptions({ name: 'MedicalSchedule' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: '',
  doctorId: '',
  status: undefined,
  date: ''
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const doctorList = ref([])// 用户列表

/** 查询排班列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ScheduleApi.getSchedulePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}


/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ScheduleApi.deleteSchedule(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/**获取医师列表 */
const getDoctorList = async () => {
  try {
    const response = await DoctorApi.getDoctorList()
    console.log('response:', response)
    doctorList.value = response
    console.log('获取的父用户列表：', doctorList.value)
  } catch (error) {
    console.error('获取父用户列表失败:', error)
    message.error('获取父用户列表失败')
  }
}


/** 修改用户状态 */
const handleStatusChange = async (row: ScheduleApi.ScheduleVO) => {
  try {
    // 修改状态的二次确认
    const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用'
    await message.confirm('确认要 [' + text + '] [' + row.doctorName + '] 医师在 [' + row.date + '] 的排班吗？' )
    // 发起修改状态
    await ScheduleApi.updateScheduleStatus(row.id, row.status)
    // 刷新列表
    await getList()
  } catch {
    // 取消后，进行恢复按钮
    row.status =
      row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ScheduleApi.exportSchedule(queryParams)
    download.excel(data, '排班列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getDoctorList()
})
</script>
